package com.imooc.springcloud;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.UUID;

/**
 * @desc
 * @author zkw
 * @date 2021-03-29
 */
@RestController
@Slf4j
public class JwtController {

    @Autowired
    private JwtService jwtService;

    @Autowired
    private RedisTemplate redisTemplate;

    @PostMapping("login")
    @ResponseBody
    public AuthResponse login(@RequestParam("username")String username,
                              @RequestParam("password")String password) {
        Account account = Account.builder()
                .username(username)
                .build();
        //todo 验证username + password

        String token = jwtService.token(account);
        account.setToken(token);
        account.setRefreshToken(UUID.randomUUID().toString());

        redisTemplate.opsForValue().set(account.getRefreshToken(), account);

        return AuthResponse.builder()
                .account(account)
                .code(AuthResponseCode.SUCCESS)
                .build();

    }

    @PostMapping("refresh")
    @ResponseBody
    public AuthResponse refresh(@RequestParam String refreshToken) {
        //验证token是否存在
        Account account = (Account) redisTemplate.opsForValue().get(refreshToken);
        if (account==null) {
            return AuthResponse.builder()
                    .code(AuthResponseCode.USER_NOT_FOND)
                    .build();
        }
        String token = jwtService.token(account);
        account.setToken(token);
        account.setRefreshToken(UUID.randomUUID().toString());
        //删除旧的token
        redisTemplate.delete(refreshToken);
        redisTemplate.opsForValue().set(account.getRefreshToken(), account);
        return AuthResponse.builder()
                .account(account)
                .code(AuthResponseCode.SUCCESS)
                .build();
    }

    @GetMapping("verify")
    @ResponseBody
    public AuthResponse verify(@RequestParam String token,
                               @RequestParam String username) {

        boolean success = jwtService.verify(token, username);
        return AuthResponse.builder()
                .code(success ? AuthResponseCode.SUCCESS : AuthResponseCode.INVALID_TOKEN)
                .build();

    }

}
